<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-09-14 10:27:54
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-06-07 15:25:27
 */

namespace Ldy\Controller;

use Ldy\Controller\BaseAdmin;
use Ldy\Lib\Grid;
use Ldy\Lib\Form;
use Ldy\Lib\Show;
use Ldy\Models\SysApi;
use think\Request;

class ApiManage extends BaseAdmin{

    protected $title = "API管理";

    private $action = ['ALL'=>'全部','GET'=>'GET','POST'=>'POST','PUT'=>'PUT','DELETE'=>'DELETE'];

    protected function grid(){

        $grid = new Grid(new SysApi());

        $grid->outTree()->hidePage();
        
        $grid->column('name','接口名称');
        $grid->column('id','ID');
        $grid->column('path','匹配路径');
        $grid->column('action','请求方式')->using([
            'ALL'=>['label'=>'全部','type'=>'success'],
            'GET'=>['label'=>'GET','type'=>'success'],
            'POST' => ['label'=>'POST','type'=>'success'],
            'PUT' => ['label'=>'PUT', 'type'=>'success'],
            'DELETE'=>['label'=>'DELETE','type'=>'danger']
        ]);
        $grid->column('bz', '备注');

        return $grid;
    }

    protected function detail(int $id)
    {
        $show = new Show(SysApi::find($id));

        $show->field('name','接口名称');
        $show->field('id','ID');
        $show->field('path','匹配路径');
        $show->field('action','请求方式')->using([
            'ALL'=>['label'=>'全部','type'=>'success'],
            'GET'=>['label'=>'GET','type'=>'success'],
            'POST' => ['label'=>'POST','type'=>'success'],
            'PUT' => ['label'=>'PUT', 'type'=>'success'],
            'DELETE'=>['label'=>'DELETE','type'=>'danger']
        ]);
        $show->field('bz', '备注');

        return $show;
        
    }

    protected function form(){

        $form = new Form(new SysApi());
        
        $model = $form->model();

        $allDept = $model->cascaderOption();

        $form->cascader('parent_id', '上级分组')->options($allDept)->checkStrictly()->emitPath();

        $form->text('name', '接口名称');
        $form->text('path', '匹配路径')->required();
        $form->select('action', '请求方式')->options($this->action)->value('ALL');
        $form->number("rand", "排序")->value(1)->btnRight();
        $form->textarea('bz', "备注");

        return $form;
    }

    public function destroy(Request $request, Int $id){
        $model = SysApi::where('parent_id', $id)->select();
        if(!$model->isEmpty()) return $this->errorJson('存在子部门，请先删除该部门下面的所有子部门！');
        SysApi::destroy($id);
        SysApi::delApi($id);
        return $this->successJson($id,'删除成功！');
    }
}